package com.open.capacity.sign.service.impl;


import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.Daily;
import com.open.capacity.common.model.Dayoff;
import com.open.capacity.common.model.Sign;
import com.open.capacity.common.model.SysParam;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.sign.Util.ApplicationContextUtil;
import com.open.capacity.sign.dao.DailyDao;
import com.open.capacity.sign.dao.DayoffDao;
import com.open.capacity.sign.dao.SignDao;
import com.open.capacity.sign.service.DailyService;
import com.open.capacity.sign.service.DayoffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class dayoffServiceImpl  implements DayoffService {
    @Autowired
    private DayoffDao dayoffDao;

    @Autowired
    private SignDao signDao;
    @Override
    public PageResult<Dayoff> dayoffManage(Map<String, Object> params) throws ServiceException {
        try {
            int total = dayoffDao.count(params);
            List<Dayoff> list = Collections.emptyList();
            if (total > 0) {
                PageUtil.pageParamConver(params, true);
                list = dayoffDao.findList(params);//查询所有日报信息

            }
            return PageResult.<Dayoff>builder().data(list)
                    .code(0).count((long) total).build();//收集所有数据
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }


    /**
     * 休期提交
     * @param dayoff
     * @return
     */
    @Override
    public Result dayoffSubmitOrUpdate(Dayoff dayoff) {
        //休期添加
        try {
            //判定添加的日期是否有重复的，id不为它的自带id
            //若有重复树，返回表中已有该日期；不能提交多次相同日期
            Boolean isHave=checkedThisDayoff(dayoff);
            if(isHave){
                return Result.succeed(-1,"有重复的日期，不能多次提交");
            }else {//没有重复的
                if (dayoff.getId() != null) {//此处id不为null，为修改

                    if(dayoff.getPutState()==1){
                        //如果已经执行；不能修改
                        Result.succeed(-2, "已经执行，不能修改");
                    }else{
                        Boolean isExState=checkedThisExState(dayoff);
                        if(isExState){//如果添加的是异常数据，则需要修改异常状态为异常
                            dayoff.setExState(1);
                        }else{dayoff.setExState(0);}
                        Integer submit = dayoffDao.dayoffUpdate(dayoff);
                        return Result.succeed(submit, "操作成功！");
                    }
                } else {//此处为添加；添加又需要判定添加的是否为异常数据
                    Boolean isExState=checkedThisExState(dayoff);
                    if(isExState){//如果添加的是异常数据，则需要修改异常状态为异常
                        dayoff.setExState(1);
                    }else{dayoff.setExState(0);}
                    Integer submit = dayoffDao.dayoffSubmit(dayoff);
                    return Result.succeed(submit, "操作成功！");
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }
        return null;
    }

    @Override
    public List<Dayoff> findAllDayoffs(Map<String, Object> params) throws ServiceException {
        try {
            List<Dayoff> dayoffExcels = new ArrayList<>();
            List<Dayoff> list = dayoffDao.findList(params);

            for (Dayoff dayoff : list) {
                Dayoff dayoffExcel = new Dayoff();
                BeanUtils.copyProperties(dayoff, dayoffExcel);
                dayoffExcels.add(dayoffExcel);
            }
            return dayoffExcels;
        } catch (BeansException e) {
            throw new ServiceException(e);
        }
    }

    @Override
    public Result dayoffDelete(Dayoff dayoff) {
        try {
            //数据恢复：将生效变成无效；将签到表中的当前时间的签到状态重新定义；
            Integer reback=0;
            Integer update = dayoffDao.dayoffDelete(dayoff);
            String historyDate=dayoff.getTime();
            Integer back=getHistoryDayoff(historyDate);
            if(update==1&&back==1){
                reback=1;
                return Result.succeed(reback, "删除成功！,数据修改成功");
            }else if(update==1){
                reback=2;
                return  Result.succeed(reback, "删除成功！数据修改失败");
            }else if(back==1){
                reback=3;
                return  Result.succeed(reback, "删除失败！数据修改成功");
            }else{
                return  Result.succeed(reback, "操作失败");
            }

        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    private Integer getHistoryDayoff(String historyDate) {
        List<Sign> signs=getSignsByTime(historyDate) ;
        int res=0;
        for(Sign s:signs){
            String signIn=s.getSignin();
            Integer instate=checkedSignInState(signIn);
            s.setIstate(instate);
            String signOut=s.getSigout();
            Integer outstate= checkedSignOutState(signOut);
            s.setOstate(outstate);
            res=updateSignState(s);
        }
        return res;
    }
    //修改签到表中的状态
    private int updateSignState(Sign sign) {
        int res=signDao.updateSignState(sign);
        return res;
    }
    /**
     * 查询签退时间 早于18点是早退
     * @param signIn
     * @return
     */
    private Integer checkedSignOutState(String signIn) {
        Integer resultState=0;
        String ds=getSigOutTime();
        Integer t=signIn.compareTo(ds);
        if(t==1){
            resultState=1;
        }else {
            resultState=2;
        }
        return resultState;
    }
    private String getSigOutTime() {
        String key="sigOutTime";
        SysParam sysParam=new SysParam();
        sysParam.setKey(key);
        String sigOutTime=signDao.getParamByKey(sysParam);
        return sigOutTime;
    }
    //检测签到时间对应的签到状态
    private Integer checkedSignInState(String signIn) {
        Integer resultState=0;
        String ds=getSignInTime();
        Integer t=signIn.compareTo(ds);
        if(t==1){
            resultState=2;
        }else {
            resultState=1;
        }
        return resultState;
    }
    private String getSignInTime() {
        String key="signInTime";
        SysParam sysParam=new SysParam();
        sysParam.setKey(key);
        String signInTime=signDao.getParamByKey(sysParam);
        return signInTime;
    }
    //根据时间参数获取
    private List<Sign> getSignsByTime(String datetime) {
        Sign sign=new Sign();
        sign.setTime(datetime);
        List<Sign> signs=signDao.getSignsByTime(sign);
        return signs;
    }
    //判定是否为异常数据
    private Boolean checkedThisExState(Dayoff dayoff) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = dateFormat.format(new Date());
        String dayoffTime=dayoff.getTime();
        boolean isExState;
        Integer t=dayoffTime.compareTo(nowTime);
        if(t==1){
            isExState=false;
        }else{
            isExState=true;
        }
        return isExState;
    }

    //判定是否有重复日期
    private Boolean checkedThisDayoff(Dayoff dayoff) {
       boolean isThisDayoff;
       int count=dayoffDao.findCountByDayoff(dayoff);
       if(count>0){
           isThisDayoff=true;
       }else{
           isThisDayoff=false;
       }
       return isThisDayoff;
    }
}
